package controllers;
import play.*;
import play.libs.*;
import play.mvc.*;
import play.cache.Cache;
import com.google.gson.Gson;
import java.util.*;
import models.*;

public class Chat extends Application {
    @Before
    private static void setup(){
        renderArgs.put("usr",getUser());
    }

    public static void index(long talkWith){
        render(talkWith); 
    }

    public static void getMessageFrom(long id){
               
        List<String> messages = (List<String>)Cache.get("chat:"+id+"to"+getUserId());
        Cache.set( "chat:"+id+"to"+getUserId(),null);
        Gson gson = new Gson();
        String msgToJson = gson.toJson(messages);
        renderJSON(msgToJson);
        deleteChatNotify();
        
    }
    public static void sendMessageTo(long recieverId){
        String message = params.get("message");
        List<String> messages = (List<String>)Cache.get("chat:"+getUserId()+"to"+recieverId);
        if(messages==null) {
            messages = new ArrayList<String>();
        }
        messages.add(message); 
        Cache.set("chat:"+getUserId()+"to"+recieverId,messages);
        sendNotifyTo(recieverId);

    }
    //向接收者发送通知
    private static void sendNotifyTo(long recieverId){
        Notify informToReceiver = Notify.getNotifyById(recieverId); 
        User sender = getUser();
        Map<String,String> chatEvent = new HashMap<String,String>();
        chatEvent.put("senderName", sender.name); 
        chatEvent.put("senderId", sender.id.toString()); 
        informToReceiver.publishChatEvent(chatEvent);
    }
    
    private static void deleteChatNotify(){
    }            


    //获取通知
    public  static void getChatNotify(long lastReceived){
           System.out.println("Chat infom is here!!!!");
           Notify inform = Notify.getNotifyById(getUserId()); 
           List notices =  await(inform.getChatEvents(lastReceived));
           inform.deleteChatEvents();
           renderJSON(notices);
    }

   
    
}
